package com.yonyou.brigade.third_parties.ctrip.bigcustomer.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.order_center.model.*;
import com.yonyou.brigade.order_center.service.*;
import com.yonyou.brigade.third_parties.ctrip.bigcustomer.service.ICtripOrderService;
import com.yonyou.brigade.third_parties.ctrip.bigcustomer.util.CtripBigCustomerRMIUtils;
import com.yonyou.brigade.third_parties.ctrip.bigcustomer.util.OrderConvert;
import com.yonyou.brigade.third_parties.ctrip.model.CtripConfig;
import com.yonyou.ybzboot.starter.common.util.StringUtil;
import com.yonyou.ybzboot.starter.mongodb.dao.IMongoDao;
import com.yonyou.ybzboot.starter.mongodb.model.CriteriaMap;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.util.List;

@Service
public class CtripOrderServiceImpl implements ICtripOrderService {

    Logger logger=LoggerFactory.getLogger(CtripOrderServiceImpl.class);

    @Autowired
    @Qualifier("briChannelServiceImpl")
    private IBriChannelService briChannelService;

    @Autowired
    @Qualifier("briFlightOrderServiceImpl")
    private IBriFlightOrderService briFlightOrderService;

    @Autowired
    @Qualifier("briFlightInfoServiceImpl")
    private IBriFlightInfoService flightInfoService;

    @Autowired
    @Qualifier("briFlightPassengerServiceImpl")
    private IBriFlightPassengerService passengerService;

    @Autowired
    @Qualifier("briHotelOrderServiceImpl")
    private IBriHotelOrderService briHotelOrderService;

    @Autowired
    @Qualifier("briHotelRoomServiceImpl")
    private IBriHotelRoomService hotelRoomService;

    @Autowired
    @Qualifier("briTrainOrderServiceImpl")
    private IBriTrainOrderService briTrainOrderService;

    @Autowired
    @Qualifier("briTrainPassengerServiceImpl")
    private IBriTrainPassengerService briTrainPassengerService;

    @Autowired
    @Qualifier("briTrainPaymentServiceImpl")
    private IBriTrainPaymentService briTrainPaymentService;

    @Autowired
    @Qualifier("briTrainTicketServiceImpl")
    private IBriTrainTicketService briTrainTicketService;

    @Autowired
    @Qualifier("userCenterServiceImpl")
    private IUserCenterService userCenterService;

    @Autowired
    private IMongoDao mongoDao;



    public void getOrderList(String tenant,String orgPk,String beginDate,String endDate,int channelId) {
        CtripConfig config=(CtripConfig)briChannelService.getChannelConfig(tenant,ChannelEnum.CTRIPBC.getName(),new CtripConfig());
        String orderResult = CtripBigCustomerRMIUtils.doRMIOrdersSearch(beginDate,endDate,config);
        if(!StringUtils.isEmpty(orderResult)) {
            JSONObject orderJSON=JSONObject.parseObject(orderResult);
            JSONObject statusJson = orderJSON.getJSONObject("Status");
            if(statusJson == null || !statusJson.getBoolean("Success")){
                logger.error("Call Ctrip failed: "+statusJson);
            }
            else {
                JSONArray itineraryArr = orderJSON.getJSONArray("ItineraryList");
                if (itineraryArr != null && itineraryArr.size() > 0) {
                    for(int i = 0; i < itineraryArr.size(); i++) {
                        JSONObject curJSON=itineraryArr.getJSONObject(i);
                        //酒店订单
                        JSONArray hotelOrderInfoArr = curJSON.getJSONArray("HotelOrderInfoList");
                        if (hotelOrderInfoArr != null && hotelOrderInfoArr.size() > 0) {
                            for (int j = 0; j < hotelOrderInfoArr.size(); j++) {
                                JSONObject orderJson = hotelOrderInfoArr.getJSONObject(j);
                                orderJson.put("channelId",channelId);
                                String orderId = orderJson.getString("OrderID");
                                try {
                                    saveHotel(orderJson, orderId, tenant);
                                } catch (ParseException e) {
                                    logger.error("保存酒店信息时类型转换出现错误！",e);
                                }
                            }
                            logger.info(hotelOrderInfoArr.toJSONString());
                        }
                        //机票订单
                        JSONArray flightOrderArr=curJSON.getJSONArray("FlightOrderInfoList");
                        if (flightOrderArr != null && flightOrderArr.size() > 0) {
                            for (int j = 0; j < flightOrderArr.size(); j++) {
                                JSONObject orderJson = flightOrderArr.getJSONObject(j);
                                orderJson.put("channelId",channelId);
                                //目前不会拉取退改签订单
                                if (orderJson.getJSONArray("RefundInfo") == null && orderJson.getJSONArray("FlightChangeInfo") == null) {
                                    String orderId = orderJson.getJSONObject("BasicInfo").getString("OrderID");
                                    try {
                                        saveFlight(orderJson, orderId, tenant);
                                    } catch (ParseException e) {
                                        logger.error("保存机票信息时类型转换出现错误！",e);
                                    }
                                }
                            }
                            logger.info(flightOrderArr.toJSONString());
                        }
                        //火车票订单
                        JSONArray trainOrderArr=curJSON.getJSONArray("TrainOrderInfoList");
                        if (trainOrderArr != null && trainOrderArr.size() > 0) {
                            for (int j = 0; j < trainOrderArr.size(); j++) {
                                JSONObject orderJson = trainOrderArr.getJSONObject(j);
                                orderJSON.put("channelId",channelId);
                                String orderId = orderJson.getJSONObject("BasicInfo").getString("OrderID");
                                try {
                                    //火车票目前如果有退改签的话，保存的是退改签之后的信息，订单退改签之前的信息没保存
                                    saveTrain(orderJson, orderId, tenant);
                                } catch (ParseException e) {
                                    logger.error("保存火车票信息时类型转换出现错误！",e);
                                }
                            }
                            logger.info(trainOrderArr.toJSONString());
                        }
                    }
                }
            }
        }

    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void saveHotel (JSONObject orderJson, String orderId, String tenant) throws ParseException {
        BriHotelOrder hotelOrder = null;
        hotelOrder = OrderConvert.getBriHotelOrderByJSON (orderJson);
        hotelOrder.setTenant(tenant);
        // 补全用户信息
        if (StringUtil.isNotEmpty(orderJson.getString("PreEmployeeID"))){
            try {
                UcUserDto ucUser = userCenterService.getCompleteUcUserDtoByPersonCode(orderJson.getString("PreEmployeeID"), tenant);
                if (null != ucUser) {
                    hotelOrder.setOrgPk(ucUser.getOrgPk());
                    hotelOrder.setDeptPk(ucUser.getDeptPk());
                    hotelOrder.setDepartment(ucUser.getDeptName());
                    hotelOrder.setUserId(ucUser.getUserId());
                }
            }catch (Exception e){
                logger.error("用户中心查询用户信息出错getOrderList.saveHotel" + e.getMessage());
            }
        }
        // mongodb save
        CriteriaMap criteriaMap = new CriteriaMap();
        criteriaMap.put("OrderInfo.OrderNo",orderId);
        List<JSONObject> ordersources = mongoDao.findByMap(criteriaMap,JSONObject.class,"ctrip_hotel_orders");
        if(ordersources != null && ordersources.size() > 0) {
            mongoDao.deleteByMap(criteriaMap,"ctrip_hotel_orders");
            mongoDao.getMongoTemplate().save(orderJson,"ctrip_hotel_orders");
        }
        else {
            mongoDao.getMongoTemplate().insert(orderJson,"ctrip_hotel_orders");
        }
        //end mongodb save
        if (hotelOrder != null) {
            Wrapper<BriHotelOrder> briHotelOrderWrapper = new EntityWrapper<>();
            briHotelOrderWrapper.where("order_no={0}", orderId);
            List<BriHotelOrder> briHoteltOrders = briHotelOrderService.selectList(briHotelOrderWrapper);
            if (briHoteltOrders != null && briHoteltOrders.size() > 0) {
//                briHotelOrderService.update(hotelOrder, briHotelOrderWrapper);
                briHotelOrderService.delete(briHotelOrderWrapper);
                briHotelOrderService.insert(hotelOrder);
            } else {
                briHotelOrderService.insert(hotelOrder);
            }
            //酒店房间及入住人信息
            Wrapper<BriHotelRoom> briHotelRoomWrapperWrapper = new EntityWrapper<>();
            briHotelRoomWrapperWrapper.where("order_no={0}", orderId);
            hotelRoomService.delete(briHotelRoomWrapperWrapper);
            List<BriHotelRoom> briHotelRooms = null;
            briHotelRooms = OrderConvert.getBriHotelRoomByJSON(orderJson, orderId);
            if (briHotelRooms != null && briHotelRooms.size() > 0) {
                hotelRoomService.insertBatch(briHotelRooms);
            }
            // end 存储酒店房间及入住人信息
        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void saveFlight (JSONObject orderJson, String orderId, String tenant) throws ParseException {
        BriFlightOrder flightOrder = null;
        flightOrder = OrderConvert.getBriFlightOrderByJSON(orderJson);
        flightOrder.setTenant(tenant);
        // 补全用户信息
        if (StringUtil.isNotEmpty(orderJson.getJSONObject("BasicInfo").getString("EmployeeID"))){
            try {
                UcUserDto ucUser = userCenterService.getCompleteUcUserDtoByPersonCode(orderJson.getJSONObject("BasicInfo").getString("EmployeeID"), tenant);
                if (null != ucUser) {
                    flightOrder.setOrgPk(ucUser.getOrgPk());
                    flightOrder.setDeptPk(ucUser.getDeptPk());
                    flightOrder.setDepartment(ucUser.getDeptName());
                    flightOrder.setUserId(ucUser.getUserId());
                }
            }catch (Exception e){
                logger.error("用户中心查询用户信息出错getOrderList.saveFlight",e);
            }
        }
        // mongodb save
        CriteriaMap criteriaMap = new CriteriaMap();
        criteriaMap.put("OrderInfo.OrderNo",orderId);
        List<JSONObject> ordersources = mongoDao.findByMap(criteriaMap,JSONObject.class,"ctrip_flight_orders");
        if(ordersources != null && ordersources.size() > 0) {
            mongoDao.deleteByMap(criteriaMap,"ctrip_flight_orders");
            mongoDao.getMongoTemplate().save(orderJson,"ctrip_flight_orders");
        }
        else {
            mongoDao.getMongoTemplate().insert(orderJson,"ctrip_flight_orders");
        }
        //end mongodb save
        if (flightOrder != null) {
            Wrapper<BriFlightOrder> briFlightOrderWrapper = new EntityWrapper<>();
            briFlightOrderWrapper.where("order_no={0}", orderId);
            List<BriFlightOrder> briFlightOrders = briFlightOrderService.selectList(briFlightOrderWrapper);
            if (briFlightOrders != null && briFlightOrders.size() > 0) {
//                briFlightOrderService.update(flightOrder, briFlightOrderWrapper);
                briFlightOrderService.delete(briFlightOrderWrapper);
                briFlightOrderService.insert(flightOrder);
            } else {
                briFlightOrderService.insert(flightOrder);
            }
            //存储航班信息
            List<BriFlightInfo> flightInfos = null;
            flightInfos = OrderConvert.getBriFlightInfoByJSON(orderJson,orderId);
            Wrapper<BriFlightInfo> briFlightInfoWrapper = new EntityWrapper<>();
            briFlightInfoWrapper.where("order_no={0}", orderId);
            flightInfoService.delete(briFlightInfoWrapper);
            if (flightInfos != null && flightInfos.size() > 0) {
                flightInfoService.insertBatch(flightInfos);
            }
            //end 存储航班信息

            //存储出行人信息
            List<BriFlightPassenger> flightPassengers = null;
            flightPassengers = OrderConvert.getBriFlightPassengerByJSON(orderJson,orderId);
            Wrapper<BriFlightPassenger> briFlightPassengerWrapper = new EntityWrapper<>();
            briFlightPassengerWrapper.where("order_no={0}", orderId);
            passengerService.delete(briFlightPassengerWrapper);
            if (flightPassengers != null && flightPassengers.size() > 0) {
                passengerService.insertBatch(flightPassengers);
            }
            //end 存储出行人信息
        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void saveTrain (JSONObject orderJson, String orderId, String tenant) throws ParseException {
        BriTrainOrder trainOrder = null;
        trainOrder = OrderConvert.getBriTrainOrderByJSON(orderJson);
        trainOrder.setTenant(tenant);
        // 补全用户信息
        if (StringUtil.isNotEmpty(orderJson.getJSONObject("BasicInfo").getString("EmployeeID"))){
            try {
                UcUserDto ucUser = userCenterService.getCompleteUcUserDtoByPersonCode(orderJson.getJSONObject("BasicInfo").getString("EmployeeID"), tenant);
                if (null != ucUser) {
                    trainOrder.setOrgPk(ucUser.getOrgPk());
                    trainOrder.setDeptPk(ucUser.getDeptPk());
                    trainOrder.setDepartment(ucUser.getDeptName());
                    trainOrder.setUserId(ucUser.getUserId());
                }
            }catch (Exception e){
                logger.error("用户中心查询用户信息出错getOrderList.saveTrain",e);
            }
        }
        // mongodb save
        CriteriaMap criteriaMap = new CriteriaMap();
        criteriaMap.put("OrderInfo.OrderNo",orderId);
        List<JSONObject> ordersources = mongoDao.findByMap(criteriaMap,JSONObject.class,"ctrip_train_orders");
        if(ordersources != null && ordersources.size() > 0) {
            mongoDao.deleteByMap(criteriaMap,"ctrip_train_orders");
            mongoDao.getMongoTemplate().save(orderJson,"ctrip_train_orders");
        }
        else {
            mongoDao.getMongoTemplate().insert(orderJson,"ctrip_train_orders");
        }
        //end mongodb save
        if (trainOrder != null) {
            Wrapper<BriTrainOrder> briTrainOrderWrapper = new EntityWrapper<>();
            briTrainOrderWrapper.where("order_no={0}", orderId);
            List<BriTrainOrder> briTrainOrders = briTrainOrderService.selectList(briTrainOrderWrapper);
            if (briTrainOrders != null && briTrainOrders.size() > 0) {
//                briTrainOrderService.update(trainOrder, briTrainOrderWrapper);
                briTrainOrderService.delete(briTrainOrderWrapper);
                briTrainOrderService.insert(trainOrder);
            } else {
                briTrainOrderService.insert(trainOrder);
            }
            //end  存储火车票订单详情信息

            //出行人信息
            Wrapper<BriTrainPassenger> trainPassengerWrapper = new EntityWrapper<>();
            trainPassengerWrapper.where("order_no={0}", orderId);
            briTrainPassengerService.delete(trainPassengerWrapper);
            List<BriTrainPassenger> passengers = null;
            passengers = OrderConvert.getBriTrainPassngerByJSON(orderJson, orderId);
            if (passengers != null && passengers.size() > 0) {
                for (int k = 0; k < passengers.size(); k++) {
                    BriTrainPassenger briTrainPassenger = passengers.get(k);
                    String cardNo = briTrainPassenger.getCardNo();
                    //票信息
                    Wrapper<BriTrainTicket> trainTicketWrapper = new EntityWrapper<>();
                    trainTicketWrapper.where("card_no={0}", cardNo).andNew("order_no={0}", orderId);
                    briTrainTicketService.delete(trainTicketWrapper);
                    List<BriTrainTicket> tickets = null;
                    tickets = OrderConvert.getBriTrainTicketByJSON(orderJson, cardNo,orderId);
                    if (tickets != null && tickets.size() > 0) {
                        briTrainTicketService.insertBatch(tickets);
                    }
                    //end  票信息
                }
                briTrainPassengerService.insertBatch(passengers);
            }
            //end  出行人信息

            //支付信息
            Wrapper<BriTrainPayment> trainPaymentWrapper = new EntityWrapper<>();
            trainPaymentWrapper.where("order_no={0}", orderId);
            briTrainPaymentService.delete(trainPaymentWrapper);
            List<BriTrainPayment> payments = null;
            payments = OrderConvert.getBriTrainPaymentByJSON(orderJson, orderId);
            if (payments != null && payments.size() > 0) {
                briTrainPaymentService.insertBatch(payments);
            }
            //end  支付信息
        }
    }
}
